var $ = window.$;
var jade = require('jade');
var animate = require('../../util/animate');
var event = require('../../core/event');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var config = require('../../core/config');
var sound = require('../audio/sound');
var notify = require('../notify/ui');
var frac = require('../../util/frac');

var _inited = false;

/**
 * bpm列表
 */

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		event.bind(event.events.key.up, 'timelist', this);
		event.lock('key', 'timelist');
		_inited = true;
	},

	setManager: function (ma) {
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(param.key == 27){
			this.hide();
			return event.result.stopAll;
		}
	},

	save: function () {
		if(this.changed){
			event.trigger(event.events.timing.change);
		}
	},

	sync: function() {
		var list = this.manager.getAll();
		if(!list || !list.length){
			return;
		}
		var html = jade.renderFile('./tmpl/timing/list.jade', list);
		this.list.html(html);
	},

	fillInputSpan: function(li){
		var span = li.find('span');
		var param = li.data('value').split(',');
		var multiplier = li.data('multiplier');
		if(multiplier == "undefined"){
			multiplier = "";
		}
		this.parent.find("#timelist_bpm").val(span.eq(1).html().replace(/\(.*?\)/, ""));
		this.parent.find("#timelist_beat").val(+param[0] + 1);
		this.parent.find("#timelist_subdivi").val(param[1]);
		this.parent.find("#timelist_divi").val(param[2]);
		$("#timelist_multiplier").val(multiplier);
	},

	fillInput: function(param){
		this.parent.find("#timelist_bpm").val(param.bpm);
		this.parent.find("#timelist_beat").val(+param.beat[0] + 1);
		this.parent.find("#timelist_subdivi").val(param.beat[1]);
		this.parent.find("#timelist_divi").val(param.beat[2]);
	},

	show: function(param){
		this.changed = false;
		var tmpl = jade.compileFile('./tmpl/timing/dialog.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_timelist');
		this.list = this.parent.find("#timelist_list");
		this.parent.on('click','.g_barhead i', function () {
			self.hide();
		});
		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'close'){
				self.save();
				self.hide();
			}else if(type == 'add'){
				//找到已有new节点
				var old = self.list.find(".new");
				if(!old.size()){
					var time = sound.stableTime();
					var beat = self.manager.timeToBeat(time);
					//不能放到0位置
					if(beat[0] == 0 && beat[1] == 0){
						beat[1] = 1;
					}
					var _new = {
						beat: beat,
						bpm: 120
					};
					self.fillInput(_new);
					old = $('<li class="new" data-value="'+beat.join(',')+'"><span>'+self.beatToParam(beat)+'</span><span>'+_new.bpm+'</span></li>');
					self.list.append(old);
					self.list.find('.curr').removeClass('curr');
					old.addClass('curr');
				}else{
					self.fillInputSpan(old);
					//todo 需要同步hint红线吗?
				}
			}else if(type == 'del'){
				var target = self.list.find('.curr');
				if(!target.size()){
					return;
				}

				var param = target.data("value").split(',');
				if(param[0] == 0 && param[1] == 0){
					return;
				}
				target.remove();
				if(!target.hasClass('new')){
					self.manager.remove({beat:param});
					event.trigger(event.events.grid.bpm);
				}
				self.changed = true;
			}else if(type == 'sync'){
				var target = self.list.find('.curr');
				if(!target.size()){
					return;
				}
				var bpm = +self.parent.find("#timelist_bpm").val() || 120;
				var beat = [0, 0, 4];
				beat[0] = (+self.parent.find("#timelist_beat").val() - 1) || 0;
				beat[1] = +self.parent.find("#timelist_subdivi").val() || 0;
				beat[2] = +self.parent.find("#timelist_divi").val() || 1;

				if(beat[0] < 0){
					beat[0] = 0;
				}
				if(beat[2] == 0){
					beat[2] = 1;
				}
				var multiplierVal =  $("#timelist_multiplier").val();
				var multiplier = multiplierVal ? parseFloat(multiplierVal) : null;

				var span = target.find('span');
				var old = target.data('value').split(',');
				if(target.hasClass('new')){
					var ret = self.manager.add({beat:beat, bpm:bpm, multiplier:multiplier});
					if(!ret){
						return;
					}
					target.removeClass('new');
				}else{
					var ret = self.manager.change({beat: old}, {beat:beat, bpm: bpm, multiplier:multiplier});
					if(!ret){
						return;
					}
				}
				span.eq(0).html(self.beatToParam(beat));
				span.eq(1).html(bpm + "(" + multiplier + "x)");
				target.data('value', beat.join(','));
				event.trigger(event.events.grid.line, beat);
				event.trigger(event.events.grid.bpm);
				self.changed = true;
			}
		});

		//点击item, 选中, 高亮位置
		this.list.on('click','li', function(e) {
			var target = $(this);
			var _param = target.data("value").split(",");
			_param = util.parseIntArray(_param);
			if(_param[0] == 0 && _param[1] == 0){
				notify.addNotify({
					msg: config.i18n("tip05")
				});
			}
			self.fillInputSpan(target);

			if(!target.hasClass('curr')){
				self.list.find('.curr').removeClass('curr');
				target.addClass('curr');
			}

			event.trigger(event.events.grid.line, _param);
		});


		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent).then(function(){
			//填充数据
			self.sync();
			//有参数的情况, 处理参数
			if(param){
				var list = self.manager.getAll();
				if(!list || !list.length){
					return;
				}
				for(var i = 0;i<list.length;i++){
					if(frac.compare(list[i].beat, param) == 0){
						var target = self.list.find('li').eq(i);
						self.fillInputSpan(target);
						target.addClass('curr');
						event.trigger(event.events.grid.line, param);
						break;
					}
				}
			}
		});
		event.trigger(event.events.global.blur);
	},

	//显示的beat, 从1开始
	beatToParam: function(beat) {
		return [+beat[0]+1,':',beat[1],'/',beat[2]].join('');
	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbind(event.events.key.up, 'timelist');
		});
		event.trigger(event.events.grid.line, null);
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;